package com.hjq.interceptor;

import com.hjq.utils.CurrentHolder;
import com.hjq.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle");
        String[] urls = {"/login", "/register"};
        String[] methods = {"POST", "PUT", "DELETE"};
        // 对于非get请求拦截
        if(Arrays.asList(methods).contains(request.getMethod())){
            // 对于登录注册放行
            if (Arrays.asList(urls).contains(request.getRequestURI())) {
                return true;
            }else{
                // token验证
                String token = request.getHeader("token");
                // 无token，拦截
                if (token == null) {
                    response.setStatus(401);
                    return false;
                }
                // 有token，解析token，判断有效性
                else {
                    try {
                        Claims claims = JwtUtils.parseJWT(token);
                        // 保存当前用户ID
                        CurrentHolder.setCurrentId((Long.valueOf(claims.get("id").toString())));
                        return true;
                    } catch (Exception e) {
                        response.setStatus(401);
                        return false;
                    }//try
                }//else
            }//else
        }
        // 对于get请求直接放行
        else{
            return true;
        }
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
        //     释放当前用户ID
        CurrentHolder.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }

}
